package com.chuanshiyidao.huawei;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.iap.Iap;
import com.huawei.hms.iap.entity.OrderStatusCode;
import com.huawei.hms.iap.entity.PurchaseResultInfo;
import com.huawei.hms.iap.util.IapClientHelper;
import com.huawei.hms.support.account.AccountAuthManager;
import com.huawei.hms.support.account.request.AccountAuthParams;
import com.huawei.hms.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.support.account.result.AuthAccount;
import com.huawei.hms.support.account.service.AccountAuthService;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    private static String EMAIL = "email";
    private static String USER_POSTS = "user_posts";

    private static final String URL = "https://brolegend-s.msgame.org/Web/huaweitoken.php?code=";
    private static final String PAY_BACK_URL = "https://brolegend-s.msgame.org/Web/huaweipay/notify.php?code=";
    private static final String BIND_URL = "https://brolegend-s.msgame.org/Web/bindhuawei.php";

    private ImageView btnLoginHuaWei = null;
    private ImageView btnLoginGuest = null;
    private WebView wvGame = null;
    private OkHttpClient client = null;
    private HuaweiPayManager huaweiPayManager = null;
    private HuaweiLoginManager huaweiLoginManager = null;

    private String tempGoodsId ="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        wvGame = findViewById(R.id.game_webview);
        btnLoginHuaWei = findViewById(R.id.huawei_login);
        btnLoginGuest = findViewById(R.id.guest_login);
        initWebView();
        client = new OkHttpClient();
        huaweiPayManager = new HuaweiPayManager(this);
        huaweiLoginManager = new HuaweiLoginManager(this, new LoginCallback() {
            @Override
            public void silenceLoginFailed() {
                btnLoginHuaWei.setVisibility(View.VISIBLE);
                btnLoginGuest.setVisibility(View.VISIBLE);
            }

            @Override
            public void silenceLoginSuccess(String openId) {
                getOpenIdFromOpenId(openId);
            }
        });
        if(!TextUtils.isEmpty(SpUtils.getGuestKey(this))
                && !SpUtils.getHasBind(MainActivity.this)){
            enterGame(SpUtils.getGuestKey(this));
        }else{
            huaweiLoginManager.loginSilence();
        }
    }

    public void OnClickLoginHuawei(View view) {
        huaweiLoginManager.login(8888);
    }

    public void OnClickLoginGuest(View view) {
        if(SpUtils.getHasBind(this)){
            Toast.makeText(this, "游客账号已经绑定，请使用华为账号登入。", Toast.LENGTH_SHORT).show();
            return;
        }
        String guestId = SpUtils.getGuestKey(this);
        if (guestId.isEmpty()) {
            //int random = (int)Math.floor(Math.random() * 100);
            //guestId =  random + System.currentTimeMillis() + "";
            guestId = UUID.randomUUID().toString();
            SpUtils.addGuestKey(this, guestId);
        }
        Utils.log( "guestId = " + guestId);
        enterGame(guestId);
    }

//    public void onClickLoginFacebook(View view){
//        String guestId = SpUtils.getGuestKey(this);
//        bindFacebookGuestId = guestId;
//        if (AccessToken.getCurrentAccessToken() == null) {
//            //   loginButton.performClick();
//            LoginManager.getInstance()
//                    .logInWithReadPermissions(this, Arrays.asList(EMAIL, USER_POSTS));
//        } else {
//             //FacebookLogin.login((Activity) context, "facebook", AccessToken.getCurrentAccessToken().getToken());
//            Map<String, String> map = new HashMap<String, String>();
//            map.put("token", AccessToken.getCurrentAccessToken().getUserId());
//            enterGame(map.get("token"));
//        }
//    }
//
//    private void initFbLogin() {
//        LoginManager.getInstance()
//            .registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
//                @Override
//                public void onSuccess(LoginResult loginResult) {
//                    HashMap<String, String> map = new HashMap<String, String>();
//                    map.put("token", loginResult == null ? ""
//                            :  loginResult.getAccessToken() == null ? ""
//                            :  loginResult.getAccessToken().getUserId());
//
//                    enterGame(map.get("token"));
//                    if (!TextUtils.isEmpty(bindFacebookGuestId)) {
//                        uploadGuestIdFacebookId(bindFacebookGuestId, map.get("token"));
//                    }
//                }
//
//                @Override
//                public void onCancel() {
//                    Toast.makeText(MainActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
//                }
//
//                @Override
//                public void onError(FacebookException error) {
//                    Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//                }
//            });
//    }

    private void initWebView() {
        //AdjustBridge.registerAndGetInstance(getApplication(), game_webview);
        wvGame.setWebContentsDebuggingEnabled(true);
        wvGame.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // return super.shouldOverrideUrlLoading(view, url);
                //String uri = url.toString();
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false; //false ： 由 WebView處理 URL 。
                } else {
                    // handleIntent(uri.toString());
                    return true;  //true ： 自行處理 URL 。         }
                }
            }

        });
        wvGame.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Utils.log("alert:" + message);
                return super.onJsAlert(view, url, message, result);
            }

        });


        WebSettings setting = wvGame.getSettings();
        setting.setJavaScriptEnabled(true);
        setting.setDomStorageEnabled(true);
        setting.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        setting.setAppCachePath(appCachePath);
        setting.setAllowFileAccess(true);
        setting.setAppCacheEnabled(true);

        //AdjustBridge.registerAndGetInstance(getApplication(), game_webview);
        //   game_webview.setDefaultHandler(DefaultHandler())
        wvGame.addJavascriptInterface(new H5ToNative(new GameCallback() {
            @Override
            public void callback(int code, String message, HashMap<String, String> map) {
                switch (code) {
                    case 0:
                        tempGoodsId = TextUtils.isEmpty(map.get("goodsId")) ? "" : map.get("goodsId");
                        if(!TextUtils.isEmpty(SpUtils.getGuestKey(MainActivity.this))
                                && !SpUtils.getHasBind(MainActivity.this)){
                            OnClickLoginHuawei(null);
                        }else{
                            pay(tempGoodsId);
                        }
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                }
            }
        }), "jsbridge");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //授权登录结果处理，从AuthAccount中获取Authorization Code
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 9999){
            //华为支付前登录
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                //登录成功，获取用户的帐号信息和Authorization Code
                AuthAccount authAccount = authAccountTask.getResult();
                Utils.log("serverAuthCode:" + authAccount.getAuthorizationCode());
                getOpenIdFromCode(authAccount.getAuthorizationCode(), requestCode);
            } else {
                Toast.makeText(this, "登录失败\nerrorMsg:"
                        + authAccountTask.getException().getMessage(), Toast.LENGTH_SHORT).show();
                //登录失败
                Utils.log("sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
            }

        }else if (requestCode == 8888) {
            //华为登录
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                //登录成功，获取用户的帐号信息和Authorization Code
                AuthAccount authAccount = authAccountTask.getResult();
                Utils.log("serverAuthCode:" + authAccount.getAuthorizationCode());
                getOpenIdFromCode(authAccount.getAuthorizationCode(), requestCode);
            } else {
                Toast.makeText(this, "登录失败\nerrorMsg:"
                        + authAccountTask.getException().getMessage(), Toast.LENGTH_SHORT).show();
                //登录失败
                Utils.log("sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
            }
        } else if (requestCode == 7777) {
            //华为支付
            if (data == null) {
                Log.e("onActivityResult", "data is null");
                return;
            }
            // 调用parsePurchaseResultInfoFromIntent方法解析支付结果数据
            PurchaseResultInfo purchaseResultInfo = Iap.getIapClient(this).parsePurchaseResultInfoFromIntent(data);
            Gson gson = new Gson();
            final String jsonStr = gson.toJson(purchaseResultInfo);
            Utils.log("jsonStr:" + jsonStr);
            final String jsCode = "javascript:payback(\"" + Uri.encode(jsonStr) + "\")";
            Utils.log("jsCode:" + jsCode);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    wvGame.evaluateJavascript(jsCode, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            Utils.log("js callback :" + value);
                        }
                    });
                }
            });

            switch (purchaseResultInfo.getReturnCode()) {
                case OrderStatusCode.ORDER_STATE_CANCEL:
                    // 用户取消
                    Utils.log("用户取消支付");
                    break;
                case OrderStatusCode.ORDER_STATE_FAILED:
                case OrderStatusCode.ORDER_PRODUCT_OWNED:
                    // 检查是否存在未发货商品
                    Utils.log("检查是否存在未发货商品");
                    huaweiPayManager.CheckUndoneOrder();
                    break;
                case OrderStatusCode.ORDER_STATE_SUCCESS:
                    Utils.log("支付成功");
                    // 支付成功
                    String inAppPurchaseData = purchaseResultInfo.getInAppPurchaseData();
                    String inAppPurchaseDataSignature = purchaseResultInfo.getInAppDataSignature();
                    //boolean checkOrder = HuaweiPayManager.doCheck(inAppPurchaseData, inAppPurchaseDataSignature);
                    //Utils.log("checkOrder:" + checkOrder);
                    huaweiPayManager.confirmOrder(inAppPurchaseData);
                    // 使用您应用的IAP公钥验证签名
                    // 若验签成功，则进行发货
                    // 若用户购买商品为消耗型商品，您需要在发货成功后调用consumeOwnedPurchase接口进行消耗
                    break;
                default:
                    break;
            }
        }
    }

    private void pay(String goodsId) {
        if(TextUtils.isEmpty(goodsId)){
            Utils.log("goodsId is null");
            return;
        }
        huaweiPayManager.pay(goodsId);
    }

    private void enterGame(final String token) {
        if (!TextUtils.isEmpty(token)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String url = "https://www.magicstar.com.tw/yidao/hwindex.html?user_id=" + token + "&v=" + Math.random() + "&mode=3";
                    Utils.log(url);
                    wvGame.loadUrl(url + "&v=" + Math.random());
                    wvGame.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    public void getOpenIdFromCode(String code, final int requestCode) {
        Request request = new Request.Builder()
                .url(URL + utf8ToUnicode(code))
                .build();
        Utils.log("httpRequest:" + URL + utf8ToUnicode(code));
        //  Toast.makeText(this, "httpRequest:" + URL + code, Toast.LENGTH_SHORT).show();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0; i < responseHeaders.size(); i++) {
                    Utils.log(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                final String responseStr = response.body() == null ? ""
                        : response.body().string();

                Utils.log("token response :" + responseStr);
                JsonObject jsonObject = new Gson().fromJson(responseStr, JsonObject.class);
                String openId =  jsonObject.get("account").toString();
                if (!"".equals(openId)) {
                    bindGuest2Hw(SpUtils.getGuestKey(MainActivity.this), openId);
                    if(8888 == requestCode){
                        enterGame(openId);
                    }else if(9999 == requestCode){
                        pay(tempGoodsId);
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "获取openid失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                final String errorMsg = e.getMessage();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this
                                , "httpRequest failed:" + errorMsg
                                , Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void getOpenIdFromOpenId(String openId) {
        String url = "https://brolegend-s.msgame.org/Web/huaweiaccount.php?uid=" + utf8ToUnicode(openId);
        Request request = new Request.Builder()
                .url(url)
                .build();
        Utils.log("getOpenId2 :" + url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0; i < responseHeaders.size(); i++) {
                    Utils.log(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                final String responseStr = response.body() == null ? ""
                        : response.body().string();
                Utils.log("httpRequest :" + responseStr);
                if (!"0".equals(responseStr)) {
                    enterGame(responseStr);
                    bindGuest2Hw(SpUtils.getGuestKey(MainActivity.this), responseStr);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "获取openid失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                final String errorMsg = e.getMessage();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this
                                , "httpRequest2 failed:" + errorMsg
                                , Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void bindGuest2Hw(String guestId, String hwId){
        if(TextUtils.isEmpty(guestId)){
            return;
        }

        //已经绑定过，那么不在上传
        if (SpUtils.getHasBind(this)) {
            return;
        }
        if (TextUtils.isEmpty(hwId)) {
            return;
        }
        FormBody formBody = new FormBody.Builder()
                .add("account", guestId)
                .add("fbaccount", hwId).build();
        final Request request = new Request.Builder()
                .url("https://brolegend-s.msgame.org/Web/Bind.php")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Utils.log("add bind failed");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if ("0".equals(response.body().string())) {
                    SpUtils.addHasBind(MainActivity.this);
                }
            }
        });
    }

    public static String utf8ToUnicode(String inStr) {

        String url = Uri.encode(inStr);
        Utils.log("decode:" + Uri.decode(url));
        return url;
//        String prefix = "\\u";
//        StringBuilder sb = new StringBuilder();
//        char[] chars = inStr.toCharArray();
//        if (chars == null || chars.length == 0) {
//            return null;
//        }
//        for (char c : chars) {
//            sb.append(prefix);
//            sb.append(Integer.toHexString(c));
//        }
//        return sb.toString();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            new AlertDialog.Builder(this)
                    .setMessage("大俠，確定退出瑪法大陸嗎？")
                    .setPositiveButton("我要離開", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    }).setNegativeButton("繼續冒險", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create().show();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}



